package com.kedacom.freedomLabel.viewmodel;


import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.OnLifecycleEvent;
import android.support.annotation.Nullable;

import com.kedacom.freedomLabel.Options;
import com.kedacom.freedomLabel.base.BaseViewModel;
import com.kedacom.freedomLabel.model.bean.Category;
import com.kedacom.freedomLabel.model.db.AppDatabase;
import com.kedacom.freedomLabel.model.db.Converters;
import com.kedacom.freedomLabel.model.db.DataCallback;
import com.kedacom.freedomLabel.model.db.DataLoader;
import com.kedacom.freedomLabel.model.db.dao.CategoryDao;
import com.seray.scaleviewlib.utils.CacheDiskUtils;

import java.util.List;


public class ItemSelectViewModel extends BaseViewModel {

    private MutableLiveData<String[]> mColumnNamesLiveData = new MutableLiveData<>();

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    public void prepareItemColumnNames() {
        String usageCategory = CacheDiskUtils.getInstance(Options.LOCAL_USAGE_CATEGORY_FILE_NAME)
                .getString(Category.class.getSimpleName());
        if (usageCategory == null || usageCategory.isEmpty()) {
            mColumnNamesLiveData.setValue(Converters.sDefaultColumnNames);
        } else {
            CategoryDao dao = AppDatabase.getInstance().categoryDao();
            DataLoader.get(dao, usageCategory, new DataCallback<List<Category>>() {
                @Override
                public void success(@Nullable List<Category> data) {
                    if (data != null && !data.isEmpty()) {
                        Category localCategory = data.get(0);
                        String[] columnNames = localCategory.columnNames;
                        mColumnNamesLiveData.setValue(columnNames);
                    } else {
                        mColumnNamesLiveData.setValue(Converters.sDefaultColumnNames);
                    }
                }

                @Override
                public void error(@Nullable String errorMessage) {
                    mColumnNamesLiveData.setValue(Converters.sDefaultColumnNames);
                }
            });
        }
    }

    public MutableLiveData<String[]> getColumnNamesLiveData() {
        return mColumnNamesLiveData;
    }
}